<template>
  <!-- 修改高度，这里将高度从 100% 改为 600px，可按需调整 -->
  <div ref="chart" style="width: 100%; height: 600px;"></div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'BarChart',
  props: {
    chartData: {
      type: Object,
      required: true
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  watch: {
    chartData: {
      deep: true,
      handler() {
        this.$nextTick(() => {
          this.initChart()
        })
      }
    }
  },
  methods: {
    initChart() {
      // Dispose of the existing chart instance if it exists
      if (this.chart) {
        this.chart.dispose()
      }
      this.chart = echarts.init(this.$refs.chart)
      // 处理 UserStatistics.vue 传递的数据格式
      const datasets = this.chartData.datasets ? this.chartData.datasets : [{
        name: '年龄分布',
        data: this.chartData.data
      }]; 
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: datasets.map(item => item.name)
        },
        xAxis: {
          type: 'category',
          data: this.chartData.labels
        },
        yAxis: {
          type: 'value'
        },
        series: datasets.map(item => ({
          name: item.name,
          type: 'bar',
          data: item.data,
          barWidth: '40%'
        }))
      }
      this.chart.setOption(option)
    }
  },
  beforeDestroy() {
    // Dispose of the chart instance when the component is destroyed
    if (this.chart) {
      this.chart.dispose()
    }
  }
}
</script>